package com.wufun.overseas.main.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;

import com.wufun.baselibrary.utils.AppInfoUtil;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.main.service.SocketServerService;
import com.wufun.overseas.models.event.ApCreateEvent;
import com.wufun.overseas.tools.filetransfer.ApWifiManager;
import com.wufun.overseas.tools.filetransfer.ApWifiUtil;
import com.wufun.overseas.tools.filetransfer.CreateApWifiThread;
import com.wufun.overseas.tools.socket.entity.SocketConfig;
import com.wufun.overseas.tools.socket.entity.SocketStatusEvent;
import com.wufun.overseas.zxing.v1.qrcode.QRCodeUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Author: hest
 * Date:  2016/4/13
 * 面传生成二维码界面
 */
public class BuildQRCodeActivity extends MyActivity {
    private static final String TAG = BuildQRCodeActivity.class.getSimpleName();

    @Bind(R.id.qr_code_vstub)
    ViewStub viewStub;

    ImageView qr_code_img;

    private static final int POOL_SIZE = 2;
    ApWifiManager apWifiManager;
    ApWifiUtil apWifiUtil;
    ExecutorService mExecutor = null;
    Future<?> future = null;
    CreateApWifiThread createApWifiThread = null;
    private String SSID = null;
    String pwd = "";
    boolean connectedSuccess = false;
    ApWifiConnectedReceiver receiver;
    boolean serviceBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_build_qr_code);
        ButterKnife.bind(this);
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);

        setBarTitleTx(R.string.title_build_qr_code);

        mExecutor = Executors.newFixedThreadPool(POOL_SIZE);
        apWifiManager = new ApWifiManager(mContext);
        apWifiUtil = ApWifiUtil.getInstance(mContext);

        getBarBackLl().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeWifiAp();
                finish();
            }
        });

        buildApWifi();
    }


    //产生8位数随机密码
    public void getRandomPwd() {
        Random rd = new Random();
        int num;
        do {
            num = Math.abs(rd.nextInt()) % 10 + 48;//产生数字0-9的随机数
            char numChar = (char) num;
            String strNum = Character.toString(numChar);
            pwd += strNum;
        } while (pwd.length() < 8);
        LogUtils.e(TAG+">>getRandomPwd: 随机的6位密码是" + pwd);
    }

    void getSSIDName() {
        SSID = AppInfoUtil.getDeviceModel();
    }

    //创建wifi热点
    void buildApWifi() {
        showLoading(getResources().getString(R.string.build_wifi_ing_str), true);

        getRandomPwd();
        getSSIDName();
        apWifiManager.createApWifi(SSID, pwd);
        createApWifiThread = new CreateApWifiThread(mContext);
        future = mExecutor.submit(createApWifiThread);
    }

    //创建二维码
    void buildQrCode() {
        View qrView = viewStub.inflate();
        qr_code_img = (ImageView) qrView.findViewById(R.id.qr_code_img);
        String rQContent = "SSID:" + SSID + ":Pwd:" + pwd;
        Bitmap bitmap = QRCodeUtil.createQRImage(rQContent, mContext);
        qr_code_img.setImageBitmap(bitmap);
        connected2Client();
        registApWifiStatus();
    }

    //文件传输界面
    void goGameTransfer() {
        startActivity(GameTransferActivity.buildIntent(mContext, SocketConfig.SOCKET_SERVER_FLAG));
        finish();
    }

    void connected2Client() {
        Intent intent = new Intent(BuildQRCodeActivity.this, SocketServerService.class);
        this.bindService(intent, connection, Context.BIND_AUTO_CREATE);
        this.startService(intent);
    }

    void stopService() {
        if (serviceBound) {
            serviceBound=false;
            mBinder.setMonitor(false);
            unbindService(connection);
            Intent intent = new Intent(BuildQRCodeActivity.this, SocketServerService.class);
            stopService(intent);
        }
    }

    SocketServerService.SocketBinder mBinder = null;
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            LogUtils.e(TAG+"----onServiceConnected---");
            serviceBound = true;
            if (iBinder instanceof SocketServerService.SocketBinder) {
                mBinder = (SocketServerService.SocketBinder) iBinder;
                mBinder.newServerSocket();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            LogUtils.e(TAG+"----onServiceDisconnected---");
        }
    };

    void registApWifiStatus() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        receiver = new ApWifiConnectedReceiver();
        registerReceiver(receiver, filter);
    }

    //wifi 热点、打开关闭广播
    class ApWifiConnectedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)) {
                //便携式热点的状态为：10---正在关闭；11---已关闭；12---正在开启；13---已开启
                int state = intent.getIntExtra("wifi_state", 0);
                if (state == 11) {
                    showToast(getResources().getString(R.string.wifi_close_str));
                    finish();
                }
            }
        }
    }

    //wifi 热点创建
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void crateApWifiStatus(ApCreateEvent event) {
        if (event == null) {
            return;
        }
        switch (event.status) {
            case ApCreateEvent.SUCCESS:
                LogUtils.e(TAG+"onSuccess: 热点创建成功");

                if (!connectedSuccess) {
                    buildQrCode();
                    if (future != null && !future.isCancelled()) {
                        future.cancel(true);
                    }
                }
                connectedSuccess = true;
                break;
            case ApCreateEvent.FAILED:
                showToast(getResources().getString(R.string.wifi_creat_fail_str));
                break;
            default:
                break;
        }
        cancelLoading();
    }

    //Socket 连接状态
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSocketStatusEvent(SocketStatusEvent bean) {
        LogUtils.e(TAG+"onSocketStatusEvent: 0000");
        if (bean == null) {
            return;
        }
        LogUtils.e(TAG+"onSocketStatusEvent: 1111");
        switch (bean.status) {
            case SocketStatusEvent.CONNECTED_SUCCESS:
                LogUtils.e(TAG+"onSocketStatusEvent: 连接成功");
                goGameTransfer();
                break;
            case SocketStatusEvent.CONNECTED_FAILED:
                stopService();
                closeWifiAp();
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeWifiAp();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    void closeWifiAp(){
        apWifiManager.closeWifiAp();
        stopService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyRunable();
        stopService();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    void destroyRunable() {
        if (createApWifiThread != null) {
            createApWifiThread.cancelDownTimer();
        }

        if (future != null && !future.isCancelled()) {
            future.cancel(true);
        }
        if (mExecutor != null) {
            if (!mExecutor.isShutdown()) {
                mExecutor.shutdownNow();
            }
        }
    }
}
